<!--
*@Author: QWP
*@Description: 单项节点属性
*@Date 2024-08-14 10:47
-->
<template>
  <div class="app-container">
    <div class="theme-main-container">
      <div class="filter-container">
        <a-tabs v-model:activeKey="taskActiveTabs" type="card">
          <a-tab-pane tab="基本信息" key="1">
            <u-form :model="taskModel"
              :elements="baseFormEls">
            </u-form>
          </a-tab-pane>
          <a-tab-pane tab="设置处理人" key="2"  
            v-show="taskType==='UserTask'" 
            :forceRender="true">
            <a-row>
              <a-col :span="24">
                <DealUser :id="taskModel.id" :type="type" :element="ruleElement"></DealUser>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane tab="多人处理" key="3" 
            :forceRender="true"
            v-show="taskType==='UserTask' && taskModel.id.includes('byStarter') == false">
            <a-row>
              <a-col :span="24">
                <MoreDealUser :task-modeler="taskModeler" 
                  :mui-element="ruleElement" 
                  :business-object="elementBaseInfo" 
                  :type="type" >
                </MoreDealUser>
                <!-- <ElementMultiInstance :task-modeler="taskModeler" :mui-element="ruleElement" :business-object="elementBaseInfo" :type="type" ></ElementMultiInstance> -->
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>

      <!-- <u-dialog :title="title"  
        :close-on-click-modal="false"
        v-model:open="ccDefaultVisible"
        :append-to-body="true"
        :hideBtns="['submit', 'close']"
        custom-class="center-dialog">
        <div class="drawer-content">
          <CcDefault ref="copyfor" :auto-c-c-way="selectAutoCCWay.value"
                      :task_def_key="ccTask_Def_Key.value"
                      :cc-way="selectCCWay.value"></CcDefault>
        </div>
        <template #footerBefore>
          <a-space>
            <a-button @click="ccDefaultVisible = false"> 取消 </a-button>
            <a-button type="primary" @click="handleSaveCC"> 确定 </a-button>
          </a-space>
        </template>
      </u-dialog> -->

      <!-- <a-drawer
        :open="viewVisible"
        title="表单预览"
        size="95%"
        class="radius"
        :append-to-body="true"
        direction="btt"
        destroy-on-close
      >
        <preview :itemList="itemList" :dataJson="[]" :formConf="formConf" />
      </a-drawer> -->

      <!-- <a-drawer
        title="表单权限配置"
        size="100%"
        :open="formEditVisible"
        @close="cloaseDialog"
        :append-to-body="true"
        destroy-on-close
        :withHeader="false"
      >
        <div class="drawer-content">
         <FormSetting :formConf="formConf" :mapList="itemList" :formId="formId" ref="formEditSetting">
         </FormSetting>
        </div>
        <div class="drawer-footer">
          <a-button type="primary" @click="saveSetting">保存</a-button>
          <a-button @click="cloaseDialog">取消</a-button>
        </div>
      </a-drawer> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'UserTaskProperties'
})
import { ref, reactive, computed, onMounted, watch, nextTick, toRaw } from 'vue'
import { storeToRefs } from 'pinia'
import {userTaskProperties,saveUserTaskProperties} from "@bs/process/flowdesign";
import UserTask from "@b/package/penal/task/task-components/UserTask.vue";
import DealUser from './component/DealUser.vue'
import MoreDealUser from './component/MoreDealUser.vue'
import {addForm, formList, getFormEntity} from "@bs/process/processFrom";
// import preview from '@b/components/formcomponents/preview.vue';
// import CcDefault from "@b/flow/components/ccDefault.vue";
import ElementMultiInstance from "@b/package/penal/multi-instance/ElementMultiInstance.vue";
// import FormSetting from "@b/components/formcomponents/formSrtting.vue";
import { isSel } from '@/common/model/base.js'

import { useTaskRuleStore, useProcessEventStore, useProcessParamsStore  } from '@/store'
import { messageC } from '@/util/common'
import { bpmnEventBus } from '@/src/util/eventBus';
const props = defineProps<{
  userTaskId: string,
  userTaskName: string,
  businessObject: object,
  element: object,
  taskModeler: any,
  taskType: string
}>()

const { returnWays, jumpWays, ccWays, autoCCWays } = storeToRefs(useTaskRuleStore())
const { taskEventTypes, eventWays } = storeToRefs(useProcessEventStore())
const { overDueWarnings, overDueWays } = storeToRefs(useProcessParamsStore())

//是否预览表单
const viewVisible = ref(false)
//表单权限配置
const formEditVisible = ref(false)
//节点基本
const TaskModelRef = ref()
let taskModel = reactive({
  //节点id
  id:'',
  //节点名称
  name:'',
  //发送按钮名称
  send_label:'',
  //是否启用保存
  save_enable:1,
  //退回方式
  returnWay:'',
  //退回后执行方式
  runWay:'',
  //移交
  transfer:0,
  //加签
  countersign:0,
  //跳转
  jumpWay:'',
  //手动结束
  endTask:0,
  //拒绝
  refuse:0,
  //抄送
  ccWay:'',
  //自动抄送
  autoCCWay:'',
  form_type: '',
  formMap: '',
  form_url: ''
})
const formItemProps = { labelWidth: '100px', wrapCol: 24 }
const baseFormEls = reactive([
  { label: '节点编号', key: 'id', col: { span: 12 }, element: 'input', formItemProps,
    componentProps: { disabled: true }
  },
  { label: '节点名称', key: 'name', col: { span: 12 }, element: 'input',  formItemProps,
    componentProps: { 
      onChange: (e) => {
        taskModel.name = e.target.value
        updateBaseInfo('name', e.target.value)
      }
    }
  },
  { label: '发送名称', key: 'send_label', col: { span: 12 }, element: 'input',  formItemProps,
    componentProps: { 
      onChange: (e) => {
        // updateBaseInfo('send_label', e.target.value)
        // saveEdit('name', e.target.value)
      }
    }
  }
])

//节点事件
const eventClass = ref([])
//逾期
const ruleOverDue = ref({
  //生命周期
  actionCycle:'',
  //预警时间
  beforeTime:'',
  //逾期预警
  overDueWar:'',
  //逾期预警接口地址
  overDueWarUrl:'',
  //逾期处理
  overDueWay:'',
  //逾期处理接口
  overDueWayUrl:''
})
const taskActiveTabs = ref('1')
const title = ref('')
const selectCCWay = ref('')
const selectAutoCCWay = ref('')
const ccTask_Def_Key = ref('')
const ccDefaultVisible = ref(false)
const elementBaseInfo = ref({})
const type = ref('UserYask')
const ruleElement = ref(props.element)
//表单集合
const formMapList = ref([])
//表单预览json
const mapJson = ref('')
//表单基本信息
const formConf = ref(Object)
//表单字段集合
const itemList = ref([])
const fromType = ref('')
const formId = ref('')
const copyfor = ref()
const formEditSetting = ref()

onMounted(() => {
  taskModel.id = props.userTaskId;
  taskModel.name = props.userTaskName;
  proInit();
})

watch(() => props.businessObject, (nval, oval) => {
  nextTick(() => {
    resetBaseInfo()
  })
}, { immediate: false })

function resetBaseInfo() {
  elementBaseInfo.value = JSON.parse(JSON.stringify(props.element.businessObject));
  if (elementBaseInfo.value && elementBaseInfo.value.$type === "bpmn:SubProcess") {
    elementBaseInfo.value.isExpanded = elementBaseInfo.value.di?.isExpanded
  }
}

// 更新节点名称
function updateBaseInfo(key, value) {
  const attrObj = Object.create(null);
  attrObj[key] = value;
  try {
    // window.bpmnInstances.modeling.updateProperties(toRaw(props.element), taskAttr);
    window.bpmnInstances.modeling.updateProperties(toRaw(props.element), attrObj);
  } catch (error) {}
}

//加载属性
function proInit(){
  window.bpmnInstances = {
    modeler: props.taskModeler,
    modeling: props.taskModeler.get("modeling"),
    moddle: props.taskModeler.get("moddle"),
    eventBus: props.taskModeler.get("eventBus"),
    bpmnFactory: props.taskModeler.get("bpmnFactory"),
    elementFactory: props.taskModeler.get("elementFactory"),
    elementRegistry: props.taskModeler.get("elementRegistry"),
    replace: props.taskModeler.get("replace"),
    selection: props.taskModeler.get("selection")
  };

  const taskInComing = props.element.businessObject.incoming;
  if(!taskInComing) return
  const taskSourceRef = taskInComing[0].sourceRef;
  if (taskSourceRef.$type == 'bpmn:StartEvent' && taskModel.id.indexOf('_byStarter') == -1) {
    taskModel.id = props.userTaskId+'_byStarter';
    const taskAttr = Object.create(null);
    taskAttr['id'] = taskModel.id;
    window.bpmnInstances.modeling.updateProperties(toRaw(props.element), taskAttr);
  }

  const attribute = window.bpmnInstances.elementRegistry.get(taskModel.id).businessObject.$attrs
  // let tModel = JSON.parse(attribute['taskModel'] || '{}');
  // for(let key in tModel) {
  //   taskModel[key] = tModel[key]
  // }
  // userTaskProperties({task_def_key: taskModel.id}).then((res)=>{
  //   if(res.error == "200") {
  //     for(let key in (res.result.formModel ||  {})) {
  //       taskModel[key] = res.result.formModel[key]
  //     }
  //     if(!taskModel.send_label){
  //       taskModel.send_label = "提交";
  //     }
  //     if(!taskModel.save_enable ){
  //       taskModel.save_enable = 0;
  //     }
  //     taskModel.id = props.userTaskId;
  //     taskModel.name = props.userTaskName;
  //     ruleOverDue.value=res.result.ruleOverDue;
  //     eventClass.value=res.result.eventClass;
  //     fromType.value=taskModel.form_type;
  //     if(taskModel.form_type=="0"){
  //       if(taskModel.form_url) {
  //         mapJson.value = JSON.parse(taskModel.form_url);
  //         formConf.value = mapJson.value.config;
  //         itemList.value = mapJson.value.list;
  //       }
  //       else{
  //         if(taskModel.formMap) {
  //           updateAttrs();
  //         }
  //       }
  //     }
  //   }
  //   else{
  //     messageC("获取节点属性失败", "warning");
  //   }
  // });
}

//保存抄送
function handleSaveCC(){
  copyfor.value.handlerSave();
}

//保存编辑
function saveEdit() {
  // if(taskModel.form_type=="0"){
  //   this.updateAttrs();
  // }
  // let taskPropertiesParams={
  //   id: props.userTaskId,
  //   name: props.userTaskName,
  //   formModel: taskModel, // 基本信息
  //   ruleOverDue: ruleOverDue.value,
  //   eventClass: eventClass.value
  // }

  // updateBaseInfo('taskModel', JSON.stringify(taskModel))

  // return taskPropertiesParams
  // saveUserTaskProperties(taskPropertiesParams).then((res)=>{
  //   if (res.error == '200') {
  //     messageC("保存成功", "success")
  //   } else {
  //     messageC('保存失败', "error");
  //   }
  // });
}

function handlerFormEdit(){
  formId.value=taskModel.formMap;
  formConf.value = mapJson.value.config;
  itemList.value = mapJson.value.list;
  formEditVisible.value=true;
}

//保存表单权限配置
function saveSetting(){
  let formCode= formEditSetting.value.saveMap();
  taskModel.form_url=formCode;
  taskModel.formMap=formId.value;
  saveEdit();
}

//设置表单预览参数
function updateAttrs() {
  let selectOption = formMapList.value.filter((item) => {
    if (item.id == taskModel.formMap) {
      return item;
    }
  });
  if (selectOption[0].form_json == undefined) {
    mapJson.value = undefined;
    return;
  }
  else{
    mapJson.value = JSON.parse(selectOption[0].form_json);
    taskModel.form_url=selectOption[0].form_json;
    formConf.value = mapJson.value.config;
    itemList.value = mapJson.value.list;
  }
}

function updateFromType(){
  if(taskModel.form_type=="0"){
    fromType.value="0";
    updateAttrs();
  }
  else{
    fromType.value="1";
    taskModel.form_url="";
  }
}

//表单预览
function openView() {
  viewVisible.value = true;
}

//限制只能输入数字
function formatNumber(field,fieldModel) {
  if(fieldModel=="ruleForm") {
    // this.ruleForm[field] = this.ruleForm[field].toString().replace(/[^\d]/g, "");
  }
  if(fieldModel=="ruleOverDue") {
    ruleOverDue.value[field] = ruleOverDue.value[field].toString().replace(/[^\d]/g, "");
  }
}

//解决输入框无法输入
function portInput() {
  // this.$forceUpdate()
}

function cloaseDialog() {
  formEditVisible.value=false;
}

defineExpose({
  saveEdit
})
</script>

<style scoped>
.a-drawer .a-drawer__body{
  padding-top: 0px !important;
  padding-bottom:  0px !important;
}
</style>
